package com.xunua.NaoZiKongBai.UpdateUserInfoActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mmkv.MMKV;
import com.xunua.NaoZiKongBai.Base.MyActivity;
import com.xunua.NaoZiKongBai.Bean.Bmob.MyUser;
import com.xunua.NaoZiKongBai.Bean.EventBus.UpdateUserInfoEvent;
import com.xunua.NaoZiKongBai.R;
import com.xunua.NaoZiKongBai.Utils.log;
import com.xunua.NaoZiKongBai.View.RoundImageView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FetchUserInfoListener;

public class UpdateUserInfoActivity extends MyActivity {
    @BindView(R.id.update_info_back)
    ImageView updateInfoBack;
    @BindView(R.id.update_info_img_icon)
    RoundImageView updateInfoImgIcon;
    @BindView(R.id.update_info_line_icon)
    LinearLayout updateInfoLineIcon;
    @BindView(R.id.update_info_et_niko_name)
    EditText updateInfoEtNikoName;
    @BindView(R.id.updater_userinfo_tv_phone)
    TextView updaterUserinfoTvPhone;
    @BindView(R.id.updater_userinfo_et_real_name)
    EditText updaterUserinfoEtRealName;
    private Unbinder unbinder;//其实butterknife的绑定可以在MyActivity里面做的，但是该父类只有两个子类，且另一个子类我已经写好了，所以就直接在当前类中进行绑定

    private MMKV mmkv = MMKV.mmkvWithID("user_icon",MMKV.MULTI_PROCESS_MODE);

    private String base64;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_user_info);
        unbinder = ButterKnife.bind(this);
        initStarBar();
        initdata();
    }

    private void initdata() {
        BmobUser.fetchUserInfo(new FetchUserInfoListener<BmobUser>() {
            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                if (e == null) {
                    MyUser myuser = BmobUser.getCurrentUser(MyUser.class);
                    updateInfoEtNikoName.setText(myuser.getNick_name());
                    updaterUserinfoEtRealName.setText(myuser.getReal_name());
                    String mobilePhoneNumber = myuser.getMobilePhoneNumber();
                    final String s = mobilePhoneNumber.substring(0, 3)+"****"+ mobilePhoneNumber.substring(7);
                    updaterUserinfoTvPhone.setText(s);
                    final byte[] icons = mmkv.getBytes("icon", null);
                    if (icons != null) {
                        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(icons);
                        updateInfoImgIcon.setImageBitmap(BitmapFactory.decodeStream(byteArrayInputStream));
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        submitUserInfor();
        unbinder.unbind();
        super.onDestroy();
    }


    private void submitUserInfor() {
        //通知观察者 更新用户资料
        EventBus.getDefault().post(new UpdateUserInfoEvent(updateInfoEtNikoName.getText().toString().trim()==null?"":updateInfoEtNikoName.getText().toString().trim(),updaterUserinfoEtRealName.getText().toString().trim()==null?"":updaterUserinfoEtRealName.getText().toString().trim()));
    }

    private void initStarBar() {
        ImmersionBar.with(this)
                .keyboardEnable(true)//解决软键盘与底部输入框冲突问题
                .statusBarDarkFont(true)//状态栏字体颜色
                .navigationBarColor(R.color.navigationBarcolor)//导航栏颜色，不写默认黑色
                .navigationBarDarkIcon(true)//导航栏图标是深色，不写默认为亮色
                .init();//沉浸状态栏
    }

    private final int REQUEST_CODE_CHOOSE=1;
    private void postFile() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(false) // Default is `true`
                .theme(R.style.Matisse_Zhihu)//R.style.Matisse_Zhihu (light mode)      R.style.Matisse_Dracula (dark mode)
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @OnClick({R.id.update_info_back, R.id.update_info_line_icon,R.id.updater_userinfo_tv_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.update_info_back:
                //返回键
                finish();
                break;
            case R.id.update_info_line_icon:
                //更换头像
                postFile();
                break;
            case R.id.updater_userinfo_tv_phone:
                Toast.makeText(this, "不支持修改绑定手机号", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {//上传单个文件
            List<Uri> mSelected=Matisse.obtainResult(data);
            if (mSelected.size() == 1) {
                Uri uri = mSelected.get(0);
                try (InputStream inputStream = getContentResolver().openInputStream(uri)){
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);
                    updateInfoImgIcon.setImageBitmap(bm);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                try (InputStream inputStream = getContentResolver().openInputStream(uri)){
                    final byte[] b = new byte[1024 * 4];
                    int length;
                    while ((length = inputStream.read(b)) != -1) {
                        byteArrayOutputStream.write(b);
                    }
                    byteArrayOutputStream.flush();
                    final byte[] input = byteArrayOutputStream.toByteArray();
                    base64 = Base64.encodeToString(input, Base64.DEFAULT);
                    mmkv.putBytes("icon",input);
                }catch (Exception e){
                    e.printStackTrace();
                } finally {
                    try {
                        byteArrayOutputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
